package com.zzt.zt_lifecycle.life;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;

/**
 * @author: zeting
 * @date: 2022/12/19
 * * Application生命周期观察，提供整个应用进程的生命周期
 * *
 * * Lifecycle.Event.ON_CREATE只会分发一次，Lifecycle.Event.ON_DESTROY不会被分发。
 * *
 * * 第一个Activity进入时，ProcessLifecycleOwner将分派Lifecycle.Event.ON_START, Lifecycle.Event.ON_RESUME。
 * * 而Lifecycle.Event.ON_PAUSE, Lifecycle.Event.ON_STOP，将在最后一个Activit退出后后延迟分发。如果由于配置更改而销毁并重新创建活动，则此延迟足以保证ProcessLifecycleOwner不会发送任何事件。
 * *
 * * 作用：监听应用程序进入前台或后台
 */
public class ApplicationLifecycleObserver implements LifecycleEventObserver {
    private static final String TAG = "LifecycleApp";
    // 启动应用时间
    public long startAppTime = 0L;

    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
        Log.w(TAG, ">>>>>>> onStateChanged source:" + source + " event:" + event);
        if (event == Lifecycle.Event.ON_START) {
            Log.w(TAG, "App 启动");
            startAppTime = System.currentTimeMillis();
        } else if (event == Lifecycle.Event.ON_STOP) {
            Log.w(TAG, "App 结束");
            long duration = System.currentTimeMillis() - startAppTime;
            Log.w(TAG, ">>>>>>>>> 在线时间 app 3:" + duration);
        }
    }
}

